<?php

class Controller_Admin_Directory extends Controller_Admin_Template
{
	protected $template = 'admin/template';
	private $db;
	private $categories = array();

	private $moduleSettings;

	private $sizes = array(
		'tiny' => array(
			'size'    => array(
				'width'  => '140',
				'height' => '100',
			),
			'options' => array(
				'method' => 'crop'
			),
		),
		'thumbs' => array(
			'size'    => array(
				'height' => '120',
			),
			'options' => array(
				'method' => 'scale'
			),
		),
		'small' => array(
			'size'    => array(
				'height' => '150',
				'width' => '200'
			),
			'options' => array(
				'method' => 'crop'
			),
		),
		'fullsize' => array(
			'size'    => array(
				'width'  => '500',
			),
			'options' => array(
				'method' => 'scale'
			),
		),
		'benefits' => array(
			'size'    => array(
				'width'  => '690',
			),
			'options' => array(
				'method' => 'scale'
			),
		),
	);
	private $pathImages      = 'content/directory/images/';
	private $pathAttachments = 'content/directory/attachments/';
	private $pathVideos = 'content/directory/videos/';
	private $pathAudio = 'content/directory/music/';

	public function before()
	{
		parent::before();
		$this->db = Database::instance();
		$this->model = Model::factory('directory');
		$this->template->title = 'Directory managing';
		$this->template->content = '';
		$this->setup();
	}
	/*
		['levels'] = 1 - How many levels available in section.
		['fields']['items'] = ('name', 'date' => 'Date of event', ...) - fields in item editor.
		['images']['max'] = 3 - maximum image count per item.
		['images']['sizes'] = array('thumbs', 'fullsize') - sizes of image for this section. Creates all sizes, if not defined. "Tiny" will be created anyway for dashboard.
		['images']['keepOriginal'] = (true|false) - Keeps original image in "original" folder. Flase by default.
	*/

	private function setup()
	{
		$moduleSettings = array();

		$moduleSettings['text']['levels'] = 0;
		$moduleSettings['text']['fields']['items'] = array('name' => 'Title', 'text1' => 'Content');
		$moduleSettings['text']['editor']['items'] = array('text1');
		$moduleSettings['text']['actions']['items'] = array('add' => true, 'edit' => true, 'delete' => true);
		$moduleSettings['text']['sorting']['items'] = true;

		$moduleSettings['home'] = array();
		$moduleSettings['home']['levels'] = 0;
		$moduleSettings['home']['fields']['items'] = array('name' => 'Title', 'text1' => 'Content');
		$moduleSettings['home']['editor']['items'] = array('text1');
		$moduleSettings['home']['actions']['items'] = array('add' => false, 'edit' => true, 'delete' => false);
		$moduleSettings['home']['images'] = array();
		$moduleSettings['home']['fields']['images'] = array('name' => 'Title');
		$moduleSettings['home']['images']['sizes'] = array('thumbs', 'fullsize');

		$moduleSettings['events'] = array();
		$moduleSettings['events']['levels'] = 0;
		$moduleSettings['events']['attachments'] = true;
		$moduleSettings['events']['fields']['attachments'] = array('name' => 'Title');
		$moduleSettings['events']['fields']['items'] = array('name' => 'Title', 'note1' => 'Date', 'text1' => 'Content');
		$moduleSettings['events']['editor']['items'] = array('text1');
		$moduleSettings['events']['actions']['items'] = array('add' => true, 'edit' => true, 'delete' => true);
		$moduleSettings['events']['sorting']['items'] = true;
		$moduleSettings['events']['images'] = array();
		$moduleSettings['events']['fields']['images'] = array('name' => 'Title');
		$moduleSettings['events']['images']['sizes'] = array('thumbs', 'fullsize');

		$moduleSettings['calendar'] = array();
		$moduleSettings['calendar']['levels'] = 0;
		$moduleSettings['calendar']['fields']['items'] = array('name' => 'Title', 'note1' => 'Date', 'url' => 'Url', 'text1' => 'Content');
		$moduleSettings['calendar']['editor']['items'] = array('text1');
		$moduleSettings['calendar']['actions']['items'] = array('add' => true, 'edit' => true, 'delete' => true);
		$moduleSettings['calendar']['sorting']['items'] = true;
		$moduleSettings['calendar']['images'] = array();
		$moduleSettings['calendar']['images']['max'] = 1;
		$moduleSettings['calendar']['images']['sizes'] = array('thumbs', 'fullsize');

		$moduleSettings['business'] = array();
		$moduleSettings['business']['levels'] = 1;
		$moduleSettings['business']['levelRules']['0']['max']['items'] = 0;
		$moduleSettings['business']['fields']['items'] = array('name' => 'Name', 'address' => 'Address', 'phone' => 'Tel', 'url' => 'Url');
		$moduleSettings['business']['editor']['items'] = array('text1');
		$moduleSettings['business']['sorting']['items'] = true;
		$moduleSettings['business']['actions']['category'] = array('add' => true, 'edit' => true, 'delete' => true);
		$moduleSettings['business']['sorting']['categories'] = true;

		$moduleSettings['resources'] = array();
		$moduleSettings['resources']['levels'] = 1;
		$moduleSettings['resources']['levelRules']['0']['max']['items'] = 0;
		$moduleSettings['resources']['fields']['items'] = array('name' => 'Name', 'address' => 'Address', 'phone' => 'Tel', 'url' => 'Url',  'text1' => 'Description');
		$moduleSettings['resources']['editor']['items'] = array('text1');
		$moduleSettings['resources']['sorting']['items'] = true;
		$moduleSettings['resources']['actions']['category'] = array('add' => true, 'edit' => true, 'delete' => true);
		$moduleSettings['resources']['sorting']['categories'] = true;

		$moduleSettings['community'] = array();
		$moduleSettings['community']['levels'] = 1;
		$moduleSettings['community']['levelRules']['0']['max']['items'] = 0;
		$moduleSettings['community']['fields']['items'] = array('name' => 'Name', 'address' => 'Address', 'phone' => 'Tel', 'url' => 'Url', 'email' => 'E-mail', 'text1' => 'Description');
		$moduleSettings['community']['editor']['items'] = array('text1');
		$moduleSettings['community']['required']['items'] = array('name');
		$moduleSettings['community']['sorting']['items'] = true;
		$moduleSettings['community']['actions']['category'] = array('add' => true, 'edit' => true, 'delete' => true);
		$moduleSettings['community']['sorting']['categories'] = true;
		
		$moduleSettings['marketing'] = array();
		$moduleSettings['marketing']['levels'] = 0;
		$moduleSettings['marketing']['attachments'] = true;
		$moduleSettings['marketing']['fields']['attachments'] = array('name' => 'Title');
		$moduleSettings['marketing']['fields']['items'] = array('name' => 'Name', 'url' => 'Url', 'text1' => 'Description');
		$moduleSettings['marketing']['editor']['items'] = array('text1');
		$moduleSettings['marketing']['actions']['items'] = array('add' => true, 'edit' => true, 'delete' => true);
		$moduleSettings['marketing']['sorting']['items'] = true;
		$moduleSettings['marketing']['images'] = array();
		$moduleSettings['marketing']['fields']['images'] = array('name' => 'Title');
		$moduleSettings['marketing']['images']['sizes'] = array('thumbs', 'fullsize');

		$moduleSettings['membership'] = array();
		$moduleSettings['membership']['levels'] = 0;
		$moduleSettings['membership']['attachments'] = true;
		$moduleSettings['membership']['fields']['attachments'] = array('name' => 'Title');
		$moduleSettings['membership']['images'] = array();
		$moduleSettings['membership']['fields']['images'] = array('name' => 'Title');
		$moduleSettings['membership']['images']['sizes'] = array('thumbs', 'benefits');
		$moduleSettings['membership']['actions']['images'] = array('add' => false, 'edit' => true, 'delete' => false);
		$moduleSettings['membership']['fields']['items'] = array('name' => 'Name', 'text1' => 'Description');
		$moduleSettings['membership']['editor']['items'] = array('text1');
		$moduleSettings['membership']['actions']['items'] = array('add' => false, 'edit' => true, 'delete' => false);
//		$moduleSettings['membership']['sorting']['items'] = true;

		$moduleSettings['spaces'] = array();
		$moduleSettings['spaces']['levels'] = 0;
		$moduleSettings['spaces']['attachments'] = true;
		$moduleSettings['spaces']['max']['attachments'] = 1;
		$moduleSettings['spaces']['actions']['attachments'] = array('add' => false, 'edit' => true, 'delete' => false);
		$moduleSettings['spaces']['fields']['attachments'] = array('name' => 'Name');
		$moduleSettings['spaces']['actions']['items'] = array('add' => false, 'edit' => true, 'delete' => false);
//		$moduleSettings['spaces']['title']['items'] = 'address';
//		$moduleSettings['spaces']['levels'] = 0;
		/*$moduleSettings['spaces']['fields']['items'] = array(
				'number' => 'Rental $/SF',
				'address' => 'Location',
				'note1' => 'Asset Type',
				'note2' => 'CAM+ Taxes/SF',
				'note3' => 'Zoning',
				'select1' => 'Status',
				'square' => 'Square Footage',
				'name' => 'Name',
				'text1' => 'Affilication',
				'phone' => 'Phone',
				'email' => 'Email',
				'text2' => 'Note'
			);*/
/*		$moduleSettings['spaces']['source']['items']['select1'] = array(
			'before' => array('for lease' => 'For Lease', 'for sale' => 'For Sale', 'other' => 'Other')
		);
		$moduleSettings['spaces']['editor']['items'] = array('text1');
		$moduleSettings['spaces']['actions']['items'] = array('add' => true, 'edit' => true, 'delete' => true);
		$moduleSettings['spaces']['sorting']['items'] = true;*/

		$moduleSettings['about'] = array();
		$moduleSettings['about']['levels'] = 0;
		$moduleSettings['about']['attachments'] = true;
		$moduleSettings['about']['images'] = array();
		$moduleSettings['about']['images']['sizes'] = array('small', 'benefits', 'fullsize');
		$moduleSettings['about']['actions']['images'] = array('add' => true, 'edit' => true, 'delete' => true);
		$moduleSettings['about']['fields']['attachments'] = array('name' => 'Title');
		$moduleSettings['about']['fields']['items'] = array('name' => 'Name', 'text1' => 'Description');
		$moduleSettings['about']['editor']['items'] = array('text1');
		$moduleSettings['about']['actions']['items'] = array('add' => true, 'edit' => true, 'delete' => true);
		$moduleSettings['about']['sorting']['items'] = true;

		$moduleSettings['faq']['levels'] = 0;
		$moduleSettings['faq']['title']['items'] = 'text1';
		$moduleSettings['faq']['fields']['items'] = array('text1' => 'Question', 'text2' => 'Answer');
		$moduleSettings['faq']['sorting']['items'] = true;
		$moduleSettings['faq']['images']['sizes'] = array('thumbs');
		$moduleSettings['faq']['images']['keepOriginal'] = true;
		$moduleSettings['news']['levels'] = 0;
		$moduleSettings['news']['title']['items'] = 'text1';
		$moduleSettings['news']['fields']['items'] = array('date', 'text1' => 'News');
		$moduleSettings['news']['sorting']['items'] = true;
		$moduleSettings['photogallery']['levels'] = 0;
		$moduleSettings['photogallery']['fields']['items'] = array('name' => 'Gallery title', 'text1' => 'Description');
		$moduleSettings['photogallery']['images'] = true;
		//$moduleSettings['photogallery']['actions']['items'] = array('add' => false, 'edit' => true, 'delete' => false);
		$moduleSettings['videogallery']['levels'] = 0;
		$moduleSettings['videogallery']['fields']['items'] = array('name', 'url' => 'Youtube link');
		$moduleSettings['videogallery']['sorting']['items'] = true;
		$moduleSettings['store']['levels'] = 1;
		$moduleSettings['store']['levelRules']['0']['max']['items'] = 0;
		$moduleSettings['store']['fields']['items'] = array('name' => 'Beat title', 'price');
		$moduleSettings['store']['audio'][''] = true;
		$moduleSettings['store']['sorting']['items'] = true;
		$moduleSettings['cart']['levels'] = 1;
		$moduleSettings['cart']['fields']['items'] = array('name' => 'Item title', 'price', 'text1' => 'Description', 'text2' => 'Size (one per line)');
		$moduleSettings['cart']['actions']['categories'] = array('add' => false, 'edit' => true, 'delete' => false);
		$moduleSettings['cart']['sorting']['items'] = true;
		$this->moduleSettings = $moduleSettings;
	}

	private function checkSection($section)
	{
		if (!isset($this->moduleSettings[$section])) {
			throw new InvalidArgumentException('Invalid section');
		}
		$categories = $this->model->getCategories($section);
		foreach ($categories as $cat) {
			$level = 1;
			$categories[$cat['id']]['level'] = $level;
			$currentParentId = $cat['parentId'];
			while($currentParentId != 0 && $level < 15) {
				if (isset($categories[$cat['parentId']])) {
					$currentParentId = $categories[$currentParentId]['parentId'];
					$level++;
				}
			}
			if ($level < 15) {
				$categories[$cat['id']]['level'] = $level;
			} else {
				$categories[$cat['id']]['level'] = 0;
			}
		}
		$this->categories = $categories;
	}

	public function actionBrowse($section, $parentId = 0)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		if (Request::$isAjax) {
			if ('POST' == Request::$method) {
				if (isset($_POST['categories'])) {
					$action = 'categories';
				} elseif (isset($_POST['items'])) {
					$action = 'items';
				}
				if (!isset($action)) {
					$this->response->body = json_encode(array('answer' => 'error'));
					$this->response->send();;
				}
				switch ($action) {
					case 'items':
						$items = $this->model->getItemsByCategoryId($parentId, $section);
						break;
					case 'categories':
						$items = $this->model->getCategoriesByParentId($parentId, $section);
						break;
				}
				foreach ($_POST[$action] as $k=>$v) {
					$position = ($k + 1);
					if ($items[$v]['position'] != $position) {
						Model_Table::instance('directory' . ucfirst($action))->update(array('position' => $position), (int)$v);
					}
				}
				$this->autoRender = false;
				$this->response->setHeader('Content-Type', 'application/json');
				$this->response->body = json_encode(array('answer' => 'saved'));
				return;
			}
		}
		$this->addScript('/scripts/jquery/jquery.js');
		$this->addScript('/scripts/jquery/jquery-ui.js');
		$this->addScript('/scripts/plugin/sortable.js');
		$moduleSettings = $this->moduleSettings[$section];
		$moduleSettings['fields']['items'] = isset($moduleSettings['fields']['items']) ? $moduleSettings['fields']['items'] : array();
		$moduleSettings['fields']['categories'] = isset($moduleSettings['fields']['categories']) ? $moduleSettings['fields']['categories'] : array();
		$level = ($parentId > 0 ? (string)$this->categories[$parentId]['level'] : '0');
		if (isset($moduleSettings['levelRules'][$level])) {
			$moduleSettings = array_merge($moduleSettings, $moduleSettings['levelRules'][$level]);
		}
		$this->template->content = new View('admin/categoryIndex');
		if ($parentId) {
			$category = $this->model->getCategory($parentId, $section);
			$this->template->content->currentCategory = $category;
		} else {
			$parentId = 0;
		}
		$order    = 'name';
		$orderDir = 'ASC';
		if (in_array('date', $moduleSettings['fields']['categories']) || isset($moduleSettings['fields']['categories']['date'])) {
			$order    = 'date';
			$orderDir = 'DESC';
		}
		if (isset($moduleSettings['sorting']['categories']) ? $moduleSettings['sorting']['categories'] === true : false) {
			$order    = 'position';
			$orderDir = 'ASC';
		}
		$categories = $this->model->getCategoriesByParentId($parentId, $section, $order, $orderDir);
		$order    = 'name';
		$orderDir = 'ASC';
		if (isset($moduleSettings['title']['items'])) {
			$order = $moduleSettings['title']['items'];
		}
		if (in_array('date', $moduleSettings['fields']['items']) || isset($moduleSettings['fields']['items']['date'])) {
			$order    = 'date';
			$orderDir = 'DESC';
		}
		if (isset($moduleSettings['sorting']['items']) ? $moduleSettings['sorting']['items'] === true : false) {
			$order    = 'position';
			$orderDir = 'ASC';
		}
		$items      = $this->model->getItemsByCategoryId($parentId, $section, $order, $orderDir);
		$images     = $this->model->getImages($section);
		$itemImages = array();
		foreach ($images as $image) {
			$itemImages[$image['itemId']][] = $image;
		}
		$this->template->content->parentId   = $parentId;
		$this->template->content->section    = $section;
		$this->template->content->categories = $categories;
		$this->template->content->allCategories = $this->categories;
		$this->template->content->items      = $items;
		$this->template->content->images     = $itemImages;
		$this->template->content->pathImages  = $this->pathImages;
		$this->template->content->moduleSettings = $moduleSettings;
	}

	public function actionItem($section, $itemId)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$this->template->content = new View('admin/itemIndex');
		$item = $this->model->getItem($itemId, $section);
		$moduleSettings = $this->moduleSettings[$section];
		$level = ($item['categoryId'] > 0 ? (string)$this->categories[$item['categoryId']]['level'] : '0');
		if (isset($moduleSettings['levelRules'][$level])) {
			$moduleSettings = array_merge($moduleSettings, $moduleSettings['levelRules'][$level]);
		}
		$images      = $this->model->getItemImages($item['id'], $section);
		$videos      = $this->model->getItemVideos($item['id'], $section);
		if ($videos) {
			$this->addStyle('/styles/jquerytools/overlay.css');
			$this->addScript('/scripts/jquery/jquery.js');
			$this->addScript('/scripts/jquerytools/jquery.tools.min.js');
			$this->addScript('/scripts/plugin/player.js');
		}
		$attachments = $this->model->getItemAttachments($item['id'], $section);
		$audio = $this->model->getItemAudio($item['id'], $section);
		$this->template->content->section          = $section;
		$this->template->content->item             = $item;
		$this->template->content->images           = $images;
		$this->template->content->pathImages       = $this->pathImages;
		$this->template->content->videos           = $videos;
		$this->template->content->pathVideos       = '/' . $this->pathVideos;
		$this->template->content->attachments      = $attachments;
		$this->template->content->audio            = $audio;
		$this->template->content->pathAttachments  = $this->pathAttachments;
		$this->template->content->pathAudio        = $this->pathAudio;
		$this->template->content->backUrl          = Request::$controller . 'browse/' . $section  . '/' . $item['categoryId'] . '/';
		$this->template->content->moduleSettings = $moduleSettings;
	}

	public function actionAddCategory($section, $parentId = 0)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$category = $this->model->getCategory($parentId, $section);
		if (!$category && $parentId != 0) {
			throw new InvalidArgumentException('Invalid category ID.');
		} else {
			$this->actionEditCategory($section, null, $parentId);
		}
	}

	public function actionEditCategory($section, $id, $parentId = null)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$moduleSettings = $this->moduleSettings[$section];
		$this->template->content = new View('admin/form');
		$this->template->content->section = $section;
		$this->template->content->title = 'Add new category';
		$fields = isset($moduleSettings['fields']['categories']) ? $moduleSettings['fields']['categories'] : array();
		$form = new Form('category');
		if ((in_array('name', $fields) || isset($fields['name'])) || !count($fields)) {
			$form->text('name', (isset($fields['name'])? $fields['name'] : 'Name'))
				->attribute('size', 40)
				->rule('maxLength', 128);
		}
		if (in_array('select1', $fields) || isset($fields['select1'])) {
			$select1 = array();
			if (isset($moduleSettings['source']['items']['select1']['before'])) {
				$select1 = $moduleSettings['source']['items']['select1']['before'];
			}
			if (isset($moduleSettings['source']['items']['select1']['query'])) {
				$source = $this->db->query($moduleSettings['source']['items']['select1']['query'])->fetchAll();
				$key = (isset($moduleSettings['source']['items']['select1']['value']) ? $moduleSettings['source']['items']['select1']['value'] : 'id');
				$value = (isset($moduleSettings['source']['items']['select1']['name']) ? $moduleSettings['source']['items']['select1']['name'] : 'name');
				if ($source) {
	    			foreach ($source as $row) {
	    				$select1[$row[$key]] = $row[$value];
	    			}
				} else {
				    $formError = isset($moduleSettings['source']['items']['select1']['message']) ? $moduleSettings['source']['items']['select1']['message'] : 'Error in select1 field.';
				}
			}
			$form->select('select1', $select1, (isset($fields['select1'])? $fields['select1'] : '&nbsp;'));
		}
		if (in_array('select2', $fields) || isset($fields['select2'])) {
			$select2 = array();
			if (isset($moduleSettings['source']['items']['select2']['before'])) {
				$select2 = $moduleSettings['source']['items']['select2']['before'];
			}
			if (isset($moduleSettings['source']['items']['select2']['query'])) {
				$source = $this->db->query($moduleSettings['source']['items']['select2']['query'])->fetchAll();
				$key = (isset($moduleSettings['source']['items']['select2']['value']) ? $moduleSettings['source']['items']['select2']['value'] : 'id');
				$value = (isset($moduleSettings['source']['items']['select2']['name']) ? $moduleSettings['source']['items']['select2']['name'] : 'name');
				if ($source) {
	    			foreach ($source as $row) {
	    				$select2[$row[$key]] = $row[$value];
	    			}
				} else {
				    $formError = isset($moduleSettings['source']['items']['select2']['message']) ? $moduleSettings['source']['items']['select2']['message'] : 'Error in select2 field.';
				}
			}
			$form->select('select2', $select2, (isset($fields['select2'])? $fields['select2'] : '&nbsp;'));
		}
		if (in_array('checkbox1', $fields) || isset($fields['checkbox1'])) {
			$form->checkbox('checkbox1', '', (isset($fields['checkbox1'])? $fields['checkbox1'] : '&nbsp;'));
		}
		if (in_array('checkbox2', $fields) || isset($fields['checkbox2'])) {
			$form->checkbox('checkbox2', '', (isset($fields['checkbox2'])? $fields['checkbox2'] : '&nbsp;'));
		}
		if (in_array('text1', $fields) || isset($fields['text1'])) {
			$form->textarea('text1', (isset($fields['text1'])? $fields['text1'] : 'Description'))->attribute('cols', 100)->attribute('rows', 15);
		}
		if (in_array('text2', $fields) || isset($fields['text2'])) {
			$form->textarea('text2', (isset($fields['text2'])? $fields['text2'] : 'Description'))->attribute('cols', 100)->attribute('rows', 15);
		}
		$form->submit('submit', 'Save');
		if (isset($moduleSettings['required']['categories'])) {
			foreach ($moduleSettings['required']['categories'] as $field) {
				if (isset($form->elements[$field])) {
					$form->elements[$field]->rule('required');
				}
			}
		}
		if ($id) {
			$category = $this->model->getCategory($id, $section);
			$parentId = $category['parentId'];
			$this->template->content->title = 'Add new category';
			$form->loadValues($category);
		}
		if (Request::$method == 'POST') {
			if ($form->validate()) {
				$alias = Url::safe((isset($form->elements['name']) ? $form->elements['name']->value : ''));
				$alias = $alias != '' ? $alias : 'category';
				$getNewAlias = false;
				if ($id) {
					$categoryAlias = substr($category['alias'], 0, strrpos($category['alias'], '-'));
					$categoryAlias = $categoryAlias ? $categoryAlias : $category['alias'];
				} else {
					$getNewAlias = true;
				}
				if (($id !== null ? ($categoryAlias != $alias) : false)) {
					if (is_numeric(substr($category['alias'], strrpos($category['alias'], '-'), 1)) || substr($category['alias'], 0, strrpos($category['alias'], '-')) == '') {
						$getNewAlias = true;
					} else {
						$alias = $category['alias'];
					}
				}
				if ($getNewAlias) {
					$nextNumber = Model::factory('directory')->getNextNumber('directoryCategories', $alias, $section);
					if ($nextNumber == 1) {
						if (count($this->db->query('SELECT 1 FROM `directoryCategories` WHERE `alias`=?', $alias))) {
							$alias .= '-2';
						}
					} else {
						$alias = $alias . '-' . $nextNumber;
					}
				}
				//echo $alias; die();
				if ($id) {
					$values = $form->getModified();
					$values['alias'] = $alias;
					$values['parentId'] = $parentId;
					$values['section'] = $section;
					Model_Table::instance('directoryCategories')->update($values, $id);
				} else {
					$values = $form->getValues();
					$cnt = 0;
					Model_Table::instance('directoryItems')->keys['string'] = 'token';
					while (true === Model_Table::instance('directoryCategories')->exists(($token = System::random('alphanuml', 6))) && $cnt < 3) {
						$cnt++;
					}
					$values['token'] = $token;
					$values['alias'] = $alias;
					$values['parentId'] = $parentId;
					$values['section'] = $section;
					Model_Table::instance('directoryCategories')->insert($values);
				}
				$this->response->redirect(Request::$controller . 'browse/' . $section  . '/' . ($parentId ? $parentId . '/' : ''));
			}
		}
		if ($parentId) {
			$this->template->content->parentId = $parentId;
		}
		if (isset($formError)) {
		    $form = $formError;
		}
		$this->template->content->form = $form;
	}

	public function actionAddItem($section, $categoryId = 0)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$category = $this->model->getCategory($categoryId, $section);
		if (!$category && $categoryId != 0) {
			throw new InvalidArgumentException('Invalid category ID.');
		} else {
			$this->actionEditItem($section, null, $categoryId);
		}
	}

	public function actionEditItem($section, $id, $categoryId = null)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$moduleSettings = $this->moduleSettings[$section];
		$this->template->content = new View('admin/form');
		$this->template->content->section = $section;
		$this->template->content->title = 'Add new item';
		$fields = isset($moduleSettings['fields']['items']) ? $moduleSettings['fields']['items'] : array();
		$form = new Form('item');
		$form->labelWidth = '120px';
		//Если не установлены поля для отображения, будет выведено поле `name`
		if ((in_array('name', $fields) || isset($fields['name'])) || !count($fields)) {
			$form->text('name', (isset($fields['name'])? $fields['name'] : 'Name'))
				->attribute('size', 40)
				->rule('maxLength', 128);
		}
		if (in_array('date', $fields) || isset($fields['date'])) {
			$form->text('date', (isset($fields['date'])? $fields['date'] : 'Date'))
                ->rule('date')
				->rule('maxLength', 10)
				->attribute('class', 'DatePicker')
				->attribute('size', 20);
			//Подключаем календарь.
			$this->addScript('/scripts/jquery/jquery.js');
			$this->addScript('/scripts/jquery/jquery-ui.js');
			$this->addScript('/scripts/jquery/timepicker/timepicker.js');
			$this->addScript('/scripts/plugin/datepicker.js');
			$this->addLink(array(
				'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
		}
		if (in_array('dateTime', $fields) || isset($fields['time'])) {
			$form->text('dateTime', (isset($fields['time'])? $fields['time'] : 'Date and Time'))
                ->rule('datetime')
				->attribute('size', 40)
				->attribute('class', 'TimePicker')
				->rule('maxLength', 64);
			//Подключаем календарь со временем.
			$this->addScript('/scripts/jquery/jquery.js');
			$this->addScript('/scripts/jquery/jquery-ui.js');
			$this->addScript('/scripts/jquery/timepicker/timepicker.js');
			$this->addScript('/scripts/plugin/timepicker.js');
			$this->addLink(array(
				'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
		}
		if (in_array('note1', $fields) || isset($fields['note1'])) {
			$form->text('note1', (isset($fields['note1'])? $fields['note1'] : 'Note'))
				->attribute('size', 40)
				->rule('maxLength', 64);
		}
		if (in_array('note2', $fields) || isset($fields['note2'])) {
			$form->text('note2', (isset($fields['note2'])? $fields['note2'] : 'Note'))
				->attribute('size', 40)
				->rule('maxLength', 64);
		}
		if (in_array('note3', $fields) || isset($fields['note3'])) {
			$form->text('note3', (isset($fields['note3'])? $fields['note3'] : 'Note'))
				->attribute('size', 40)
				->rule('maxLength', 64);
		}
		if ((in_array('select1', $fields) || isset($fields['select1']))) {
			$select1 = array();
			if (isset($moduleSettings['source']['items']['select1']['before'])) {
				$select1 = $moduleSettings['source']['items']['select1']['before'];
			}
			if (isset($moduleSettings['source']['items']['select1']['query'])) {
				$source = $this->db->query($moduleSettings['source']['items']['select1']['query'])->fetchAll();
				$key = (isset($moduleSettings['source']['items']['select1']['value']) ? $moduleSettings['source']['items']['select1']['value'] : 'id');
				$value = (isset($moduleSettings['source']['items']['select1']['name']) ? $moduleSettings['source']['items']['select1']['name'] : 'name');
				if ($source) {
	    			foreach ($source as $row) {
	    				$select1[$row[$key]] = $row[$value];
	    			}
				} else {
				    $formError = isset($moduleSettings['source']['items']['select1']['message']) ? $moduleSettings['source']['items']['select1']['message'] : 'Error in select1 field.';
				}
			}
			$form->select('select1', $select1, (isset($fields['select1'])? $fields['select1'] : '&nbsp;'));
		}
		if ((in_array('select2', $fields) || isset($fields['select2']))) {
			$select2 = array();
			if (isset($moduleSettings['source']['items']['select2']['before'])) {
				$select2 = $moduleSettings['source']['items']['select2']['before'];
			}
			if (isset($moduleSettings['source']['items']['select2']['query'])) {
				$source = $this->db->query($moduleSettings['source']['items']['select2']['query'])->fetchAll();
				$key = (isset($moduleSettings['source']['items']['select2']['value']) ? $moduleSettings['source']['items']['select2']['value'] : 'id');
				$value = (isset($moduleSettings['source']['items']['select2']['name']) ? $moduleSettings['source']['items']['select2']['name'] : 'name');
				if ($source) {
	    			foreach ($source as $row) {
	    				$select2[$row[$key]] = $row[$value];
	    			}
				} else {
				    $formError = isset($moduleSettings['source']['items']['select2']['message']) ? $moduleSettings['source']['items']['select2']['message'] : 'Error in select2 field.';
				}
			}
			$form->select('select2', $select2, (isset($fields['select2'])? $fields['select2'] : '&nbsp;'));
		}
		if ((in_array('select3', $fields) || isset($fields['select3']))) {
			$select3 = array();
			if (isset($moduleSettings['source']['items']['select3']['before'])) {
				$select3 = $moduleSettings['source']['items']['select3']['before'];
			}
			if (isset($moduleSettings['source']['items']['select3']['query'])) {
				$source = $this->db->query($moduleSettings['source']['items']['select3']['query'])->fetchAll();
				$key = (isset($moduleSettings['source']['items']['select3']['value']) ? $moduleSettings['source']['items']['select3']['value'] : 'id');
				$value = (isset($moduleSettings['source']['items']['select3']['name']) ? $moduleSettings['source']['items']['select3']['name'] : 'name');
				if ($source) {
	    			foreach ($source as $row) {
	    				$select3[$row[$key]] = $row[$value];
	    			}
				} else {
				    $formError = isset($moduleSettings['source']['items']['select3']['message']) ? $moduleSettings['source']['items']['select3']['message'] : 'Error in select3 field.';
				}
			}
			$form->select('select3', $select3, (isset($fields['select3'])? $fields['select3'] : '&nbsp;'));
		}
		if (in_array('checkbox1', $fields) || isset($fields['checkbox1'])) {
			$form->checkbox('checkbox1', '', (isset($fields['checkbox1'])? $fields['checkbox1'] : '&nbsp;'));
		}
		if (in_array('checkbox2', $fields) || isset($fields['checkbox2'])) {
			$form->checkbox('checkbox2', '', (isset($fields['checkbox2'])? $fields['checkbox2'] : '&nbsp;'));
		}
		if (in_array('checkbox3', $fields) || isset($fields['checkbox3'])) {
			$form->checkbox('checkbox3', '', (isset($fields['checkbox3'])? $fields['checkbox3'] : '&nbsp;'));
		}
		if (in_array('address', $fields) || isset($fields['address'])) {
			$form->text('address', (isset($fields['address'])? $fields['address'] : 'Address'))
				->attribute('size', 40)
				->rule('maxLength', 64);
		}
		if (in_array('phone', $fields) || isset($fields['phone'])) {
			$form->text('phone', (isset($fields['phone'])? $fields['phone'] : 'Phone'))
				->attribute('size', 40)
				->rule('maxLength', 64);
		}
		if (in_array('email', $fields) || isset($fields['email'])) {
			$form->text('email', (isset($fields['email'])? $fields['email'] : 'E-mail'))
				->attribute('size', 40)
				->rule('maxLength', 64)
				->rule('email');
		}
		if (in_array('url', $fields) || isset($fields['url'])) {
			$form->text('url', (isset($fields['url'])? $fields['url'] : 'URL'))
				->attribute('size', 40)
				->rule('maxLength', 64)
				->rule('url');
		}
		if (in_array('price', $fields) || isset($fields['price'])) {
			$form->text('price', (isset($fields['price'])? $fields['price'] : 'Price (USD)'))
				->attribute('size', 10)
				->rule('maxLength', 10)
				->rule('float');
		}
		if (isset($moduleSettings['editor']['items'])) {
			$this->addScript('/scripts/jquery/jquery.js');
			$this->addScript('/scripts/jquery/jquery-ui.js');
			$this->addScript('/scripts/elrte/elrte.min.js');
			$this->addScript('/scripts/plugin/editor.js');
			$this->addLink(array(
				'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
			$this->addLink(array(
				'href' => '/styles/elrte/elrte.full.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
		}
		if (in_array('text1', $fields) || isset($fields['text1'])) {
			$form->textarea('text1', (isset($fields['text1'])? $fields['text1'] : 'Description'))
				->attribute('cols', 100)->attribute('rows', 15);
			if (isset($moduleSettings['editor']['items']) ? in_array('text1', $moduleSettings['editor']['items']) : false) {
				$form->elements['text1']->attribute('class', 'elrte');
			}
		}
		if (in_array('text2', $fields) || isset($fields['text2'])) {
			$form->textarea('text2', (isset($fields['text2'])? $fields['text2'] : 'Description 2'))
				->attribute('cols', 100)->attribute('rows', 15);
			if (isset($moduleSettings['editor']['items']) ? in_array('text2', $moduleSettings['editor']['items']) : false) {
				$form->elements['text2']->attribute('class', 'elrte');
			}
		}
		if (in_array('text3', $fields) || isset($fields['text3'])) {
			$form->textarea('text3', (isset($fields['text3'])? $fields['text3'] : 'Description 3'))
				->attribute('cols', 100)->attribute('rows', 15);
			if (isset($moduleSettings['editor']['items']) ? in_array('text3', $moduleSettings['editor']['items']) : false) {
				$form->elements['text3']->attribute('class', 'elrte');
			}
		}
		/*=================================*/
		if (in_array('number', $fields) || isset($fields['number'])) {
			$form->text('number', (isset($fields['number'])? $fields['number'] : 'Number'))
				->attribute('size', 40)
				->rule('maxLength', 10);
		}
		if (in_array('days', $fields) || isset($fields['days'])) {
			$form->text('days', (isset($fields['days'])? $fields['days'] : 'Days on market'))
				->attribute('size', 40)
				->rule('maxLength', 10);
		}
		if (in_array('square', $fields) || isset($fields['square'])) {
			$form->text('square', (isset($fields['square'])? $fields['square'] : 'Square Footage'))
				->attribute('size', 40)
				->rule('maxLength', 10);
		}
		/*=================================*/
		$form->submit('submit', 'Save');
		if (isset($moduleSettings['required']['items'])) {
			foreach ($moduleSettings['required']['items'] as $field) {
				if (isset($form->elements[$field])) {
					$form->elements[$field]->rule('required');
				}
			}
		}
		if ($id) {
			$item = $this->model->getItem($id, $section);
			$categoryId = $item['categoryId'];
			$this->template->content->title = 'Add new item';
			$form->loadValues($item);
		}
		if (Request::$method == 'POST') {
			if ($form->validate()) {
				$alias = Url::safe((isset($form->elements['name']) ? $form->elements['name']->value : ''));
				$alias = $alias != '' ? $alias : $section;
				$getNewAlias = false;
				if ($id) {
					$itemAlias = substr($item['alias'], 0, strrpos($item['alias'], '-'));
					$itemAlias = $itemAlias ? $itemAlias : $item['alias'];
				} else {
					$getNewAlias = true;
				}
				if (($id !== null ? ($itemAlias != $alias) : false)) {
					if (is_numeric(substr($item['alias'], strrpos($item['alias'], '-'), 1)) || substr($item['alias'], 0, strrpos($item['alias'], '-')) == '') {
						$getNewAlias = true;
					} else {
						$alias = $item['alias'];
					}
				}
				if ($getNewAlias) {
					$nextNumber = Model::factory('directory')->getNextNumber('directoryItems', $alias, $section);
					if ($nextNumber == 1) {
						if (count($this->db->query('SELECT 1 FROM `directoryItems` WHERE `alias`=?', $alias))) {
							$alias .= '-2';
						}
					} else {
						$alias = $alias . '-' . $nextNumber;
					}
				}
				if ($id) {
					$values = $form->getModified();
					if (isset($values['date'])) {
						if ($values['date'] == '') {
							$values['date'] = null;
						}
					}
					if (isset($values['dateTime'])) {
						if ($values['dateTime'] == '') {
							$values['dateTime'] = null;
						}
					}
					$values['alias'] = $alias;
					$values['categoryId'] = $categoryId;
					$values['section'] = $section;
					Model_Table::instance('directoryItems')->update($values, $id);
				} else {
					$values = $form->getValues();
					$cnt = 0;
					Model_Table::instance('directoryItems')->keys['string'] = 'token';
					while (true === Model_Table::instance('directoryItems')->exists(($token = System::random('alphanuml', 3))) && $cnt < 3) {
						$cnt++;
					}
					$values['token'] = $token;
					if (isset($values['date']) ? ($values['date'] == '') : true) {
						$values['date'] = null;
					}
					if (isset($values['dateTime'])) {
						if ($values['dateTime'] == '') {
							$values['dateTime'] = null;
						}
					}
					$values['alias'] = $alias;
					$values['categoryId'] = $categoryId;
					$values['section'] = $section;
					Model_Table::instance('directoryItems')->insert($values);
				}
				if ($id) {
					$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $id . '/');
				} else {
					$this->response->redirect(Request::$controller . 'browse/' . $section  . '/' . ($categoryId ? $categoryId . '/' : ''));
				}
			}
		}
		if (isset($item)) {
			$this->template->content->backUrl = Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/';
		} else {
			$this->template->content->backUrl = Request::$controller . 'browse/' . $section  . '/' . $categoryId . '/';
		}
		if (isset($formError)) {
		    $form = $formError;
		}
		$this->template->content->form = $form;
	}

	public function actionAddImage($section, $itemId)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$item = $this->model->getItem($itemId, $section);
		if (!$item) {
			throw new InvalidArgumentException('Invalid item ID.');
		} else {
			$this->actionEditImage($section, null, $itemId);
		}
	}

	public function actionEditImage($section, $id, $itemId = null)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$this->template->content = new View('admin/form');
		$moduleSettings = $this->moduleSettings[$section];
		$fields = isset($moduleSettings['fields']['images']) ? $moduleSettings['fields']['images'] : array();
		$this->template->content->section = $section;
		$this->template->content->title = 'Add new image';
		$form = new Form('image');
		if ((in_array('name', $fields) || isset($fields['name']))) {
			$form->text('name', (isset($fields['name'])? $fields['name'] : 'Name'))
				->attribute('size', 40)
				->rule('maxLength', 128);
		}
		$form->file('file', 'Image file')->attribute('size', 35)->rule('extension', array('jpg', 'jpeg', 'png', 'gif'));
		if (isset($moduleSettings['editor']['items'])) {
			$this->addScript('/scripts/jquery/jquery.js');
			$this->addScript('/scripts/jquery/jquery-ui.js');
			$this->addScript('/scripts/elrte/elrte.min.js');
			$this->addScript('/scripts/plugin/editor.js');
			$this->addLink(array(
				'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
			$this->addLink(array(
				'href' => '/styles/elrte/elrte.full.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
		}
		if ((in_array('select1', $fields) || isset($fields['select1']))) {
			$select1 = array();
			if (isset($moduleSettings['source']['items']['select1']['before'])) {
				$select1 = $moduleSettings['source']['items']['select1']['before'];
			}
			if (isset($moduleSettings['source']['items']['select1']['query'])) {
				$source = $this->db->query($moduleSettings['source']['items']['select1']['query'])->fetchAll();
				$key = (isset($moduleSettings['source']['items']['select1']['value']) ? $moduleSettings['source']['items']['select1']['value'] : 'id');
				$value = (isset($moduleSettings['source']['items']['select1']['name']) ? $moduleSettings['source']['items']['select1']['name'] : 'name');
				if ($source) {
	    			foreach ($source as $row) {
	    				$select1[$row[$key]] = $row[$value];
	    			}
				} else {
				    $formError = isset($moduleSettings['source']['items']['select1']['message']) ? $moduleSettings['source']['items']['select1']['message'] : 'Error in select1 field.';
				}
			}
			$form->select('select1', $select1, (isset($fields['select1'])? $fields['select1'] : '&nbsp;'));
		}
		if ((in_array('select2', $fields) || isset($fields['select2']))) {
			$select2 = array();
			if (isset($moduleSettings['source']['items']['select2']['before'])) {
				$select2 = $moduleSettings['source']['items']['select2']['before'];
			}
			if (isset($moduleSettings['source']['items']['select2']['query'])) {
				$source = $this->db->query($moduleSettings['source']['items']['select2']['query'])->fetchAll();
				$key = (isset($moduleSettings['source']['items']['select2']['value']) ? $moduleSettings['source']['items']['select2']['value'] : 'id');
				$value = (isset($moduleSettings['source']['items']['select2']['name']) ? $moduleSettings['source']['items']['select2']['name'] : 'name');
				if ($source) {
	    			foreach ($source as $row) {
	    				$select2[$row[$key]] = $row[$value];
	    			}
				} else {
				    $formError = isset($moduleSettings['source']['items']['select2']['message']) ? $moduleSettings['source']['items']['select2']['message'] : 'Error in select2 field.';
				}
			}
			$form->select('select2', $select2, (isset($fields['select2'])? $fields['select2'] : '&nbsp;'));
		}
		if (in_array('checkbox1', $fields) || isset($fields['checkbox1'])) {
			$form->checkbox('checkbox1', '', (isset($fields['checkbox1'])? $fields['checkbox1'] : '&nbsp;'));
		}
		if (in_array('checkbox2', $fields) || isset($fields['checkbox2'])) {
			$form->checkbox('checkbox2', '', (isset($fields['checkbox2'])? $fields['checkbox2'] : '&nbsp;'));
		}
		if (in_array('text1', $fields) || isset($fields['text1'])) {
			$form->textarea('text1', (isset($fields['text1'])? $fields['text1'] : 'Description'))
				->attribute('cols', 100)->attribute('rows', 15);
			if (isset($moduleSettings['editor']['items']) ? in_array('text1', $moduleSettings['editor']['items']) : false) {
				$form->elements['text1']->attribute('class', 'elrte');
			}
		}
		if (in_array('text2', $fields) || isset($fields['text2'])) {
			$form->textarea('text2', (isset($fields['text2'])? $fields['text2'] : 'Description 2'))
				->attribute('cols', 100)->attribute('rows', 15);
			if (isset($moduleSettings['editor']['items']) ? in_array('text2', $moduleSettings['editor']['items']) : false) {
				$form->elements['text2']->attribute('class', 'elrte');
			}
		}
		$form->submit('submit', 'Save');
		if (isset($moduleSettings['required']['images'])) {
			foreach ($moduleSettings['required']['images'] as $field) {
				if (isset($form->elements[$field])) {
					$form->elements[$field]->rule('required');
				}
			}
		}
		if ($id) {
			$image = $this->model->getImage($id, $section);
			$itemId = $image['itemId'];
			$this->template->content->title = 'Edit image';
			$form->loadValues($image);
		} else {
			$form->elements['file']->rule('required');
		}
		$item = $this->model->getItem($itemId, $section);
		if (Request::$method == 'POST') {
			if ($form->validate()) {
				if ($id) {
					$alias = $image['alias'];
				} else {
					$cnt = 0;
					while (true === Model_Table::instance('directoryImages')->exists(($alias = System::random('alphanuml', 6))) && $cnt < 3) {
						$cnt++;
					}
				}
				if (isset($form->elements['file']->files[0])) {
					$files = $form->elements['file']->files;
					$file = $files[0];
					$umask = umask(0);
					$tmpDir = $this->pathImages . '_tmp/';
					if (!file_exists($tmpDir)) {
						mkdir($tmpDir, 0777, true);
					}
					$tmpFilename = $tmpDir . 'tmp.jpg';
					if (false === move_uploaded_file($file['tmp_name'], $tmpFilename)) {
						umask($umask);
						throw new Exception('File %s cannot be moved.');
					} else {
						$this->resizeImage($alias, $section);
						if ((isset($moduleSettings['images']['keepOriginal']) ? $moduleSettings['images']['keepOriginal'] : false)) {
							$fileName = $this->imagePath($alias, 'original', $section);
							if (!file_exists($imageDir = $this->imageDir($alias, 'original', $section))) {
								mkdir($imageDir, 0777, true);
							}
							copy($this->pathImages . '_tmp/tmp.jpg', $fileName);
						}
					}
					list ($imgWidth, $imgHeight, $type, $attr) = getimagesize($tmpFilename);
					$resolution = $imgWidth . 'x' . $imgHeight;
				}
				if ($id) {
					$values = $form->getModified();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					if (isset($resolution)) {
						$values['resolution'] = $resolution;
					}
					Model_Table::instance('directoryImages')->update($values, $id);
				} else {
					$values = $form->getValues();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					if (isset($resolution)) {
						$values['resolution'] = $resolution;
					}
					Model_Table::instance('directoryImages')->insert($values);
				}
				$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/');
			}
		}
		$this->template->content->backUrl = Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/';
		if (isset($formError)) {
		    $form = $formError;
		}
		$this->template->content->form = $form;
	}

	public function actionAddVideo($section, $itemId)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$item = $this->model->getItem($itemId, $section);
		if (!$item) {
			throw new InvalidArgumentException('Invalid item ID.');
		} else {
			$this->actionEditVideo($section, null, $itemId);
		}
	}

	public function actionEditVideo($section, $id, $itemId = null)
	{
		$this->addStyle('/styles/jquerytools/overlay.css');
		$this->addScript('/scripts/jquery/jquery.js');
		$this->addScript('/scripts/jquerytools/jquery.tools.min.js');
		$this->addScript('/scripts/plugin/uploadVideo.js');
		$section = strtolower($section);
		$this->checkSection($section);
		$moduleSettings = $this->moduleSettings[$section];
		$fields = isset($moduleSettings['fields']['videos']) ? $moduleSettings['fields']['videos'] : array();
		$this->template->content = new View('admin/form');
		$this->template->content->section = $section;
		$this->template->content->title = 'Add new video';
		$form = new Form('video');
		if ((in_array('name', $fields) || isset($fields['name'])) || !count($fields)) {
			$form->text('name', (isset($fields['name'])? $fields['name'] : 'Name'))
				->attribute('size', 40)
				->rule('maxLength', 128);
		}
		$form->file('file', 'Video')->attribute('size', 35);
		$moduleSettings['videos']['filetypes'] = isset($moduleSettings['videos']['extensions']) ? $moduleSettings['videos']['extensions'] : array('mp4', 'avi', 'mpeg4', 'mpg', 'divx', 'wmv', 'flv');
		$form->elements['file']->rule('extension', $moduleSettings['videos']['extensions']);
		if (isset($moduleSettings['editor']['videos'])) {
			$this->addScript('/scripts/jquery/jquery.js');
			$this->addScript('/scripts/jquery/jquery-ui.js');
			$this->addScript('/scripts/elrte/elrte.min.js');
			$this->addScript('/scripts/plugin/editor.js');
			$this->addLink(array(
				'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
			$this->addLink(array(
				'href' => '/styles/elrte/elrte.full.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
		}
		if ((in_array('select1', $fields) || isset($fields['select1']))) {
			$select1 = array();
			if (isset($moduleSettings['source']['items']['select1']['before'])) {
				$select1 = $moduleSettings['source']['items']['select1']['before'];
			}
			if (isset($moduleSettings['source']['items']['select1']['query'])) {
				$source = $this->db->query($moduleSettings['source']['items']['select1']['query'])->fetchAll();
				$key = (isset($moduleSettings['source']['items']['select1']['value']) ? $moduleSettings['source']['items']['select1']['value'] : 'id');
				$value = (isset($moduleSettings['source']['items']['select1']['name']) ? $moduleSettings['source']['items']['select1']['name'] : 'name');
				if ($source) {
	    			foreach ($source as $row) {
	    				$select1[$row[$key]] = $row[$value];
	    			}
				} else {
				    $formError = isset($moduleSettings['source']['items']['select1']['message']) ? $moduleSettings['source']['items']['select1']['message'] : 'Error in select1 field.';
				}
			}
			$form->select('select1', $select1, (isset($fields['select1'])? $fields['select1'] : '&nbsp;'));
		}
		if ((in_array('select2', $fields) || isset($fields['select2']))) {
			$select2 = array();
			if (isset($moduleSettings['source']['items']['select2']['before'])) {
				$select2 = $moduleSettings['source']['items']['select2']['before'];
			}
			if (isset($moduleSettings['source']['items']['select2']['query'])) {
				$source = $this->db->query($moduleSettings['source']['items']['select2']['query'])->fetchAll();
				$key = (isset($moduleSettings['source']['items']['select2']['value']) ? $moduleSettings['source']['items']['select2']['value'] : 'id');
				$value = (isset($moduleSettings['source']['items']['select2']['name']) ? $moduleSettings['source']['items']['select2']['name'] : 'name');
				if ($source) {
	    			foreach ($source as $row) {
	    				$select2[$row[$key]] = $row[$value];
	    			}
				} else {
				    $formError = isset($moduleSettings['source']['items']['select2']['message']) ? $moduleSettings['source']['items']['select2']['message'] : 'Error in select2 field.';
				}
			}
			$form->select('select2', $select2, (isset($fields['select2'])? $fields['select2'] : '&nbsp;'));
		}
		if (in_array('checkbox1', $fields) || isset($fields['checkbox1'])) {
			$form->checkbox('checkbox1', '', (isset($fields['checkbox1'])? $fields['checkbox1'] : '&nbsp;'));
		}
		if (in_array('checkbox2', $fields) || isset($fields['checkbox2'])) {
			$form->checkbox('checkbox2', '', (isset($fields['checkbox2'])? $fields['checkbox2'] : '&nbsp;'));
		}
		if (in_array('text1', $fields) || isset($fields['text1'])) {
			$form->textarea('text1', (isset($fields['text1'])? $fields['text1'] : 'Description'))
				->attribute('cols', 100)->attribute('rows', 15);
			if (isset($moduleSettings['editor']['items']) ? in_array('text1', $moduleSettings['editor']['items']) : false) {
				$form->elements['text1']->attribute('class', 'elrte');
			}
		}
		if (in_array('text2', $fields) || isset($fields['text2'])) {
			$form->textarea('text2', (isset($fields['text2'])? $fields['text2'] : 'Description 2'))
				->attribute('cols', 100)->attribute('rows', 15);
			if (isset($moduleSettings['editor']['items']) ? in_array('text2', $moduleSettings['editor']['items']) : false) {
				$form->elements['text2']->attribute('class', 'elrte');
			}
		}
		$form->submit('submit', 'Save')->attribute('rel', '#overlay');
		if (isset($moduleSettings['required']['videos'])) {
			foreach ($moduleSettings['required']['videos'] as $field) {
				if (isset($form->elements[$field])) {
					$form->elements[$field]->rule('required');
				}
			}
		}
		if ($id) {
			$video = $this->model->getVideo($id, $section);
			$itemId = $video['itemId'];
			$this->template->content->title = 'Edit video';
			$form->loadValues($video);
		} else {
			$form->elements['file']->rule('required');
		}
		$item = $this->model->getItem($itemId, $section);
		if (Request::$method == 'POST') {
			if ($form->validate()) {
				if ($id) {
					$alias = $video['alias'];
				} else {
					$cnt = 0;
					while (true === Model_Table::instance('directoryVideos')->exists(($alias = System::random('alphanuml', 3))) && $cnt < 3) {
						$cnt++;
					}
				}
				if (isset($form->elements['file']->files[0])) {
					$files = $form->elements['file']->files;
					$file = $files[0];
					$umask = umask(0);
					$videoDir = $this->videoDir($alias, $section);
					if (!file_exists($videoDir)) {
						mkdir($videoDir, 0777, true);
					}
					umask($umask);
					$videoPrevDir = $this->videoPrevDir($alias, $section);
					if (!file_exists($videoPrevDir)) {
						mkdir($videoPrevDir, 0777, true);
					}
					umask($umask);
					$videoFilename = $this->videoDir($alias, $section) . $alias . '.flv';
					$videoPrevFilename = $this->videoPrevDir($alias, $section) . $alias . '.jpg';
					set_time_limit(1200);
					//system('ffmpeg -y -i "' . $file['tmp_name'] . '" -ar 22050 -ab 32 -f flv "' . $videoFilename . '"');
					//system('ffmpeg -y -i "' . $file['tmp_name'] . '" -ar 22050 -ab 32 -vhook "/usr/lib/vhook/imlib2.so -x 100 -y 105 -i images/logo.png" -f flv "' . $videoFilename . '"');
					system('ffmpeg -y -i "' . $file['tmp_name'] . '" -ar 22050 -ab 32 -vhook "/usr/lib/vhook/imlib2.so -x ((W-w)-20) -y ((H-h)-20) -i images/logo.png" -f flv "' . $videoFilename . '"');
					system('ffmpeg -y -i "' . $videoFilename . '" -an -ss 00:00:01 -an -r 1 -vframes 1 -y -f image2 -s 480x360 "' . $videoPrevFilename . '"');
					Image::Watermark($videoPrevFilename, 'images/icons/playButton.gif', $this->videoPrevDir($alias, $section) . $alias . '_.jpg');
					$filesize = filesize($videoFilename);
				}
				if ($id) {
					$values = $form->getModified();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					if (isset($filesize)) {
						$values['filesize'] = $filesize;
					}
					if (isset($filename)) {
						$values['filename'] = $filename;
					}
					Model_Table::instance('directoryVideos')->update($values, $id);
				} else {
					$values = $form->getValues();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					$values['filesize'] = $filesize;
					Model_Table::instance('directoryVideos')->insert($values);
				}
				$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/');
			}
		}
		$this->template->content->backUrl = Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/';
		if (isset($formError)) {
		    $form = $formError;
		}
		$this->template->content->form = $form;
		$this->template->content->overlay = new View('admin/overlay');
	}

	public function actionAddAttachment($section, $itemId)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$item = $this->model->getItem($itemId, $section);
		if (!$item) {
			throw new InvalidArgumentException('Invalid item ID.');
		} else {
			$this->actionEditAttachment($section, null, $itemId);
		}
	}

	public function actionEditAttachment($section, $id, $itemId = null)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$moduleSettings = $this->moduleSettings[$section];
		$fields = isset($moduleSettings['fields']['attachments']) ? $moduleSettings['fields']['attachments'] : array();
		$this->template->content = new View('admin/form');
		$this->template->content->section = $section;
		$this->template->content->title = 'Add new attachment';
		$form = new Form('attachment');
		if ((in_array('name', $fields) || isset($fields['name']))) {
			$form->text('name', (isset($fields['name'])? $fields['name'] : 'Name'))
				->attribute('size', 40)
				->rule('maxLength', 128);
		}
		$form->file('file', 'Attachment')->attribute('size', 35);
		if (isset($moduleSettings['attachments']['extensions'])) {
			$form->elements['file']->rule('extension', $moduleSettings['attachments']['extensions']);
		}
		if (isset($moduleSettings['editor']['attachments'])) {
			$this->addScript('/scripts/jquery/jquery.js');
			$this->addScript('/scripts/jquery/jquery-ui.js');
			$this->addScript('/scripts/elrte/elrte.min.js');
			$this->addScript('/scripts/plugin/editor.js');
			$this->addLink(array(
				'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
			$this->addLink(array(
				'href' => '/styles/elrte/elrte.full.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
		}
		if ((in_array('select1', $fields) || isset($fields['select1']))) {
			$select1 = array();
			if (isset($moduleSettings['source']['items']['select1']['before'])) {
				$select1 = $moduleSettings['source']['items']['select1']['before'];
			}
			if (isset($moduleSettings['source']['items']['select1']['query'])) {
				$source = $this->db->query($moduleSettings['source']['items']['select1']['query'])->fetchAll();
				$key = (isset($moduleSettings['source']['items']['select1']['value']) ? $moduleSettings['source']['items']['select1']['value'] : 'id');
				$value = (isset($moduleSettings['source']['items']['select1']['name']) ? $moduleSettings['source']['items']['select1']['name'] : 'name');
				if ($source) {
	    			foreach ($source as $row) {
	    				$select1[$row[$key]] = $row[$value];
	    			}
				} else {
				    $formError = isset($moduleSettings['source']['items']['select1']['message']) ? $moduleSettings['source']['items']['select1']['message'] : 'Error in select1 field.';
				}
			}
			$form->select('select1', $select1, (isset($fields['select1'])? $fields['select1'] : '&nbsp;'));
		}
		if ((in_array('select2', $fields) || isset($fields['select2']))) {
			$select2 = array();
			if (isset($moduleSettings['source']['items']['select2']['before'])) {
				$select2 = $moduleSettings['source']['items']['select2']['before'];
			}
			if (isset($moduleSettings['source']['items']['select2']['query'])) {
				$source = $this->db->query($moduleSettings['source']['items']['select2']['query'])->fetchAll();
				$key = (isset($moduleSettings['source']['items']['select2']['value']) ? $moduleSettings['source']['items']['select2']['value'] : 'id');
				$value = (isset($moduleSettings['source']['items']['select2']['name']) ? $moduleSettings['source']['items']['select2']['name'] : 'name');
				if ($source) {
	    			foreach ($source as $row) {
	    				$select2[$row[$key]] = $row[$value];
	    			}
				} else {
				    $formError = isset($moduleSettings['source']['items']['select2']['message']) ? $moduleSettings['source']['items']['select2']['message'] : 'Error in select2 field.';
				}
			}
			$form->select('select2', $select2, (isset($fields['select2'])? $fields['select2'] : '&nbsp;'));
		}
		if (in_array('checkbox1', $fields) || isset($fields['checkbox1'])) {
			$form->checkbox('checkbox1', '', (isset($fields['checkbox1'])? $fields['checkbox1'] : '&nbsp;'));
		}
		if (in_array('checkbox2', $fields) || isset($fields['checkbox2'])) {
			$form->checkbox('checkbox2', '', (isset($fields['checkbox2'])? $fields['checkbox2'] : '&nbsp;'));
		}
		if (in_array('text1', $fields) || isset($fields['text1'])) {
			$form->textarea('text1', (isset($fields['text1'])? $fields['text1'] : 'Description'))
				->attribute('cols', 100)->attribute('rows', 15);
			if (isset($moduleSettings['editor']['items']) ? in_array('text1', $moduleSettings['editor']['items']) : false) {
				$form->elements['text1']->attribute('class', 'elrte');
			}
		}
		if (in_array('text2', $fields) || isset($fields['text2'])) {
			$form->textarea('text2', (isset($fields['text2'])? $fields['text2'] : 'Description 2'))
				->attribute('cols', 100)->attribute('rows', 15);
			if (isset($moduleSettings['editor']['items']) ? in_array('text2', $moduleSettings['editor']['items']) : false) {
				$form->elements['text2']->attribute('class', 'elrte');
			}
		}
		$form->submit('submit', 'Save');
		if (isset($moduleSettings['required']['attachments'])) {
			foreach ($moduleSettings['required']['attachments'] as $field) {
				if (isset($form->elements[$field])) {
					$form->elements[$field]->rule('required');
				}
			}
		}
		if ($id) {
			$attachment = $this->model->getAttachment($id, $section);
			$itemId = $attachment['itemId'];
			$this->template->content->title = 'Edit attachment';
			$form->loadValues($attachment);
		} else {
			$form->elements['file']->rule('required');
		}
		$item = $this->model->getItem($itemId, $section);
		if (Request::$method == 'POST') {
			if ($form->validate()) {
				if ($id) {
					$alias = $attachment['alias'];
				} else {
					$cnt = 0;
					while (true === Model_Table::instance('directoryAttachments')->exists(($alias = System::random('alphanuml', 6))) && $cnt < 3) {
						$cnt++;
					}
				}
				if (isset($form->elements['file']->files[0])) {
					$files = $form->elements['file']->files;
					$file = $files[0];
					$umask = umask(0);
					$dir = $this->attachmentDir($alias, $section);
					if (!file_exists($dir)) {
						mkdir($dir, 0777, true);
					}
					$tmpFilename = $this->attachmentDir($alias, $section) . $file['name'];
					if (false === move_uploaded_file($file['tmp_name'], $tmpFilename)) {
						umask($umask);
						throw new Exception('File %s cannot be moved.');
					}
					$filename = $file['name'];
					$filesize = filesize($tmpFilename);
				}
				if ($id) {
					$values = $form->getModified();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					if (isset($filesize)) {
						$values['filesize'] = $filesize;
					}
					if (isset($filename)) {
						$values['filename'] = $filename;
					}
					Model_Table::instance('directoryAttachments')->update($values, $id);
				} else {
					$values = $form->getValues();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					$values['filesize'] = $filesize;
					$values['filename'] = $filename;
					Model_Table::instance('directoryAttachments')->insert($values);
				}
				$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/');
			}
		}
		$this->template->content->backUrl = Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/';
		if (isset($formError)) {
		    $form = $formError;
		}
		$this->template->content->form = $form;
	}

	public function actionAddAudio($section, $itemId)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$item = $this->model->getItem($itemId, $section);
		if (!$item) {
			throw new InvalidArgumentException('Invalid item ID.');
		} else {
			$this->actionEditAudio($section, null, $itemId);
		}
	}

	public function actionEditAudio($section, $id, $itemId = null)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$moduleSettings = $this->moduleSettings[$section];
		$fields = isset($moduleSettings['fields']['audio']) ? $moduleSettings['fields']['audio'] : array();
		$this->template->content = new View('admin/form');
		$this->template->content->section = $section;
		$this->template->content->title = 'Add new audio file';
		$form = new Form('audio');
		if ((in_array('name', $fields) || isset($fields['name']))) {
			$form->text('name', (isset($fields['name'])? $fields['name'] : 'Name'))
				->attribute('size', 40)
				->rule('maxLength', 128);
		}
		$moduleSettings['audio']['extensions'] = isset($moduleSettings['audio']['extensions']) ? $moduleSettings['audio']['extensions'] : array('mp3');
		$form->file('file', 'Audio file')->attribute('size', 35)->rule('extension', $moduleSettings['videos']['extensions']);
		if (isset($moduleSettings['audio']['extensions'])) {
			$form->elements['file']->rule('extension', $moduleSettings['audio']['extensions']);
		}
		if (isset($moduleSettings['editor']['audio'])) {
			$this->addScript('/scripts/jquery/jquery.js');
			$this->addScript('/scripts/jquery/jquery-ui.js');
			$this->addScript('/scripts/elrte/elrte.min.js');
			$this->addScript('/scripts/plugin/editor.js');
			$this->addLink(array(
				'href' => '/styles/jquery-ui/ui-custom/jquery-ui.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
			$this->addLink(array(
				'href' => '/styles/elrte/elrte.full.css',
				'rel'  => 'stylesheet',
				'type' => 'text/css',
			));
		}
		if ((in_array('select1', $fields) || isset($fields['select1']))) {
			$select1 = array();
			if (isset($moduleSettings['source']['items']['select1']['before'])) {
				$select1 = $moduleSettings['source']['items']['select1']['before'];
			}
			if (isset($moduleSettings['source']['items']['select1']['query'])) {
				$source = $this->db->query($moduleSettings['source']['items']['select1']['query'])->fetchAll();
				$key = (isset($moduleSettings['source']['items']['select1']['value']) ? $moduleSettings['source']['items']['select1']['value'] : 'id');
				$value = (isset($moduleSettings['source']['items']['select1']['name']) ? $moduleSettings['source']['items']['select1']['name'] : 'name');
				if ($source) {
	    			foreach ($source as $row) {
	    				$select1[$row[$key]] = $row[$value];
	    			}
				} else {
				    $formError = isset($moduleSettings['source']['items']['select1']['message']) ? $moduleSettings['source']['items']['select1']['message'] : 'Error in select1 field.';
				}
			}
			$form->select('select1', $select1, (isset($fields['select1'])? $fields['select1'] : '&nbsp;'));
		}
		if ((in_array('select2', $fields) || isset($fields['select2']))) {
			$select2 = array();
			if (isset($moduleSettings['source']['items']['select2']['before'])) {
				$select2 = $moduleSettings['source']['items']['select2']['before'];
			}
			if (isset($moduleSettings['source']['items']['select2']['query'])) {
				$source = $this->db->query($moduleSettings['source']['items']['select2']['query'])->fetchAll();
				$key = (isset($moduleSettings['source']['items']['select2']['value']) ? $moduleSettings['source']['items']['select2']['value'] : 'id');
				$value = (isset($moduleSettings['source']['items']['select2']['name']) ? $moduleSettings['source']['items']['select2']['name'] : 'name');
				if ($source) {
	    			foreach ($source as $row) {
	    				$select2[$row[$key]] = $row[$value];
	    			}
				} else {
				    $formError = isset($moduleSettings['source']['items']['select2']['message']) ? $moduleSettings['source']['items']['select2']['message'] : 'Error in select2 field.';
				}
			}
			$form->select('select2', $select2, (isset($fields['select2'])? $fields['select2'] : '&nbsp;'));
		}
		if (in_array('checkbox1', $fields) || isset($fields['checkbox1'])) {
			$form->checkbox('checkbox1', '', (isset($fields['checkbox1'])? $fields['checkbox1'] : '&nbsp;'));
		}
		if (in_array('checkbox2', $fields) || isset($fields['checkbox2'])) {
			$form->checkbox('checkbox2', '', (isset($fields['checkbox2'])? $fields['checkbox2'] : '&nbsp;'));
		}
		if (in_array('text1', $fields) || isset($fields['text1'])) {
			$form->textarea('text1', (isset($fields['text1'])? $fields['text1'] : 'Description'))
				->attribute('cols', 100)->attribute('rows', 15);
			if (isset($moduleSettings['editor']['items']) ? in_array('text1', $moduleSettings['editor']['items']) : false) {
				$form->elements['text1']->attribute('class', 'elrte');
			}
		}
		if (in_array('text2', $fields) || isset($fields['text2'])) {
			$form->textarea('text2', (isset($fields['text2'])? $fields['text2'] : 'Description 2'))
				->attribute('cols', 100)->attribute('rows', 15);
			if (isset($moduleSettings['editor']['items']) ? in_array('text2', $moduleSettings['editor']['items']) : false) {
				$form->elements['text2']->attribute('class', 'elrte');
			}
		}
		$form->submit('submit', 'Save');
		if (isset($moduleSettings['required']['audio'])) {
			foreach ($moduleSettings['required']['audio'] as $field) {
				if (isset($form->elements[$field])) {
					$form->elements[$field]->rule('required');
				}
			}
		}
		if ($id) {
			$audio = $this->model->getAudio($id, $section);
			$itemId = $audio['itemId'];
			$this->template->content->title = 'Edit audio';
			$form->loadValues($audio);
		} else {
			$form->elements['file']->rule('required');
		}
		$item = $this->model->getItem($itemId, $section);
		if (Request::$method == 'POST') {
			if ($form->validate()) {
				if ($id) {
					$alias = $audio['alias'];
				} else {
					$cnt = 0;
					while (true === Model_Table::instance('directoryAudio')->exists(($alias = System::random('alphanuml', 6))) && $cnt < 3) {
						$cnt++;
					}
				}
				if (isset($form->elements['file']->files[0])) {
					$files = $form->elements['file']->files;
					$file = $files[0];
					$umask = umask(0);
					$dir = $this->audioDir($alias, $section);
					if (!file_exists($dir)) {
						mkdir($dir, 0777, true);
					}
					$tmpFilename = $this->audioDir($alias, $section) . $file['name'];
					if (false === move_uploaded_file($file['tmp_name'], $tmpFilename)) {
						umask($umask);
						throw new Exception('File %s cannot be moved.');
					}
					$filename = $file['name'];
					$filesize = filesize($tmpFilename);
				}
				if ($id) {
					$values = $form->getModified();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					if (isset($filesize)) {
						$values['filesize'] = $filesize;
					}
					if (isset($filename)) {
						$values['filename'] = $filename;
					}
					Model_Table::instance('directoryAudio')->update($values, $id);
				} else {
					$values = $form->getValues();
					$values['alias'] = $alias;
					$values['itemId'] = $itemId;
					$values['section'] = $section;
					$values['filesize'] = $filesize;
					$values['filename'] = $filename;
					Model_Table::instance('directoryAudio')->insert($values);
				}
				$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/');
			}
		}
		$this->template->content->backUrl = Request::$controller . 'item/' . $section  . '/' . $item['id'] . '/';
		if (isset($formError)) {
		    $form = $formError;
		}
		$this->template->content->form = $form;
	}

	private function resizeImage($alias, $section)
	{
		$moduleSettings = $this->moduleSettings[$section];
		$sizes = (isset($moduleSettings['images']['sizes']) ? $moduleSettings['images']['sizes'] : array());
		if (count($sizes) && !in_array('tiny', $sizes)) {
			$sizes[count($sizes)] = 'tiny';
		}
		$moduleSettings['images']['sizes'][count($moduleSettings['images']['sizes'])] = 'tiny';
		foreach ($this->sizes as $size => $settings) {
			if (count($sizes) == 0 || in_array($size, $sizes)) {
				$fileName = $this->imagePath($alias, $size, $section);
				if (!file_exists($imageDir = $this->imageDir($alias, $size, $section))) {
					mkdir($imageDir, 0777, true);
				}
				Image::Resize($this->pathImages . '_tmp/tmp.jpg', $settings['size'], array_merge($settings['options'], array('filename' => $fileName)));
			}
		}
	}

	private function imagePath($alias, $size, $section)
	{
		return $this->pathImages . $section . '/' . $size . '/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '.jpg';
	}

	private function imageDir($alias, $size, $section)
	{
		return $this->pathImages . $section . '/' . $size . '/' . strtolower(substr($alias, 0, 1)) . '/';
	}

	private function attachmentPath($alias, $filename, $section)
	{
		return $this->pathAttachments . $section . '/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '/' . $filename;
	}

	private function attachmentDir($alias, $section)
	{
		return $this->pathAttachments . $section . '/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '/';
	}

	private function audioPath($alias, $filename, $section)
	{
		return $this->pathAudio . $section . '/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '/' . $filename;
	}

	private function audioDir($alias, $section)
	{
		return $this->pathAudio . $section . '/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '/';
	}

	private function videoPath($alias, $section)
	{
		return $this->pathVideos . $section . '/video/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '.flv';
	}

	private function videoDir($alias, $section)
	{
		return $this->pathVideos . $section . '/video/' . strtolower(substr($alias, 0, 1)) . '/';
	}

	private function videoPrevPath($alias, $section)
	{
		return $this->pathVideos . $section . '/preview/' . strtolower(substr($alias, 0, 1)) . '/' . $alias . '.jpg';
	}

	private function videoPrevDir($alias, $section)
	{
		return $this->pathVideos . $section . '/preview/' . strtolower(substr($alias, 0, 1)) . '/';
	}

	public function actionRemoveCategory($section, $categoryId, $internal = false)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$category = $this->model->getCategory($categoryId, $section);
		$categories = $this->model->getCategoriesByParentId($category['id'], $section);
		if (count($categories)) {
			foreach ($categories as $cat) {
				$this->actionRemoveCategory($section, $cat['id'], true);
			}
		}
		$items = $this->model->getItemsByCategoryId($category['id'], $section);
		if (count($items)) {
			foreach ($items as $item) {
				$this->actionRemoveItem($section, $item['id'], true);
			}
		}
		Model_Table::instance('directoryCategories')->delete((int)$category['id']);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'browse/' . $section  . '/' . $category['parentId'] . '/');
		}
	}

	public function actionRemoveItem($section, $itemId, $internal = false)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$item        = $this->model->getItem($itemId, $section);
		$images      = $this->model->getItemImages($item['id'], $section);
		$attachments = $this->model->getItemAttachments($item['id'], $section);
		$audio = $this->model->getItemAudio($item['id'], $section);
		if (count($images)) {
			foreach ($images as $image) {
				$this->actionRemoveImage($section, $image['id'], true);
			}
		}
		if (count($attachments)) {
			foreach ($attachments as $attachment) {
				$this->actionRemoveAttachment($section, $attachment['id'], true);
			}
		}
		if (count($audio)) {
			foreach ($audio as $audioItem) {
				$this->actionRemoveAudio($section, $audioItem['id'], true);
			}
		}
		Model_Table::instance('directoryItems')->delete((int)$item['id']);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'browse/' . $section  . '/' . ($item['categoryId'] ? $item['categoryId'] : 0) . '/');
		}
	}

	public function actionRemoveAttachment($section, $attachmentId, $internal = false)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$attachment = $this->model->getAttachment($attachmentId, $section);
		$fileName = $this->attachmentPath($attachment['alias'], $attachment['filename'], $section);
		if (file_exists($fileName)) {
			unlink($fileName);
			if (FileSystem::isDirEmpty($attDir = $this->attachmentDir($attachment['alias'], $section))) {
				rmdir($attDir);
			}
		}
		Model_Table::instance('directoryAttachments')->delete((int)$attachment['id']);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $attachment['itemId'] . '/');
		}
	}

	public function actionRemoveAudio($section, $audioId, $internal = false)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$audio = $this->model->getAudio($audioId, $section);
		$fileName = $this->audioPath($audio['alias'], $audio['filename'], $section);
		if (file_exists($fileName)) {
			unlink($fileName);
			if (FileSystem::isDirEmpty($attDir = $this->audioDir($audio['alias'], $section))) {
				rmdir($attDir);
			}
		}
		Model_Table::instance('directoryAudio')->delete((int)$audio['id']);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $audio['itemId'] . '/');
		}
	}

	public function actionRemoveImage($section, $imageId, $internal = false)
	{
		$moduleSettings = $this->moduleSettings[$section];
		$section = strtolower($section);
		$this->checkSection($section);
		$image = $this->model->getImage($imageId, $section);
		$sizes = $this->sizes;
		$sizes['original'] = array();
		foreach ($sizes as $size => $options) {
			$fileName = $this->imagePath($image['alias'], $size, $section);
			if (file_exists($fileName)) {
				unlink($fileName);
				if (FileSystem::isDirEmpty($imgDir = $this->imageDir($image['alias'], $size, $section))) {
					rmdir($imgDir);
				}
			}
		}
		Model_Table::instance('directoryImages')->delete((int)$image['id']);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $image['itemId'] . '/');
		}
	}

	public function actionRemoveVideo($section, $videoId, $internal = false)
	{
		$section = strtolower($section);
		$this->checkSection($section);
		$video = $this->model->getVideo($videoId, $section);
		$videoFilename = $this->videoPath($video['alias'], $section);
		if (file_exists($videoFilename)) {
			unlink($videoFilename);
			if (FileSystem::isDirEmpty($vidDir = $this->videoDir($video['alias'], $section))) {
				rmdir($vidDir);
			}
		}
		$videoPreviewFilename = $this->videoPrevPath($video['alias'], $section);
		if (file_exists($videoPreviewFilename)) {
			unlink($videoPreviewFilename);
			if (file_exists(str_ireplace('.jpg', '_.jpg', $videoPreviewFilename))) {
				unlink(str_ireplace('.jpg', '_.jpg', $videoPreviewFilename));
			}
			if (FileSystem::isDirEmpty($vidPrevDir = $this->videoPrevDir($video['alias'], $section))) {
				rmdir($vidPrevDir);
			}
		}
		Model_Table::instance('directoryVideos')->delete((int)$video['id']);
		if (!$internal) {
			$this->response->redirect(Request::$controller . 'item/' . $section  . '/' . $video['itemId'] . '/');
		}
	}
}
?>